/**
 * @file Logger.h
 * @brief 
 * 		数据类的定义（便于转换成json格式和读取json存入结构体）
 * 		ERR LOG 等静态的LOG接口
 * 
 * @author Zyan (zyishere2001@qq.com)
 * @version 1.0
 * @date 2022-05-07
 * 
 * @copyright Copyright (c) 2022  Zyanishere2001
 * 
 * @par 修改日志:
 * V1.0_0507 TODO：queue？ loop?
 */
#ifndef _LOGGER
#define _LOGGER

#include "EventLoopThread.h"
#include "hv.h"
#include "JsonLoader.h"
#include <iostream>
#include "SafeQueue.h"
#include <ws2tcpip.h>
using namespace nlohmann;
using namespace hv;

//定义数据类
//to serialize , to pharse
namespace Custom {
	struct HostInfo {
		std::string ip;
		UINT port;
	};
	struct PacketInfo {
		UCHAR protocol;
		HostInfo src;
		HostInfo dst;
		size_t len;
		bool causion;//是否需要注意
	};
	NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(HostInfo, ip, port)
	NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(PacketInfo, protocol, src, dst, len, causion);
	
	struct Err {
		std::string Time;
		std::string err;
		std::string suggestion;
	};
	NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Err, Time, err, suggestion);

	struct Log {
		std::string Time;
		std::string type;
		std::string from;
		std::string msg;
	};
	NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Log, Time,type, from, msg);
};

class Logger{
	Logger(){};
private:
	// static EventLoopThread log_thread;
	// const EventLoopPtr& loop = log_thread.loop();

public:
	//static SafeQueue<std::vector<uint8_t>> logQueue;

	static std::string getTime() {
		time_t now = time(0);
		char* dt = ctime(&now);
		return std::string(dt);
	}

	static void ERR(std::string err, std::string suggesstion = "WOO") {
		//err数据类
		Custom::Err e{
			getTime(),
			err,
			suggesstion,
		};
		json errj = e;

		std::ofstream errlog;
		errlog.open("./logs/log.json", std::ios::app);
		if (!errlog.is_open()) {
			printf("open log.json failed\n");
		}
		JsonLoader::writeToFile(errlog, errj);
		errlog.close();
		exit(-1);
	}

	static void LOG(std::string type, std::string from, std::string msg) {
		//实例化log数据类
		Custom::Log log{
			getTime(),type, from, msg
		};
		
		//json
		json logj = log;

		//file
		std::ofstream errlog;
		errlog.open("./logs/log.json", std::ios::app);
		if (!errlog.is_open()) {
			printf("open log.json failed\n");
		}

		JsonLoader::writeToFile(errlog, logj);

		errlog.close();
	}
};

#endif